var PageCount = 0;
var PageIndex = 0;



$(window).ready(function () {
    InitGuardians();
    // $("#guardianAvatarPreview").attr("src","");
});
function InitGuardians(pageInt) {
    $.ajax("../ListGuardians",{
        type: "get",
        dataType: "json",
        data:{
            where:$("#term-9 .col-md-4 .form-control").val(),
            page:pageInt,
        },
        success: function (data) {
            if(data.message === "获取数据成功"){
                $("#term-9 .table-responsive table tbody").empty();
                $("#term-9 .pagination").empty();
                ListGuardians(data.guardiansList);
                PageIndex = data.pageInt;
                if(PageCount === 0) {
                    pagIng(data.totalPage, data.pageInt);//分页
                }
            }
        }
    });
}

function ListGuardians(data) {
    for(let i = 0;i < data.length;i++){
        var vipLevel = checkVipLevel(data[i].spend);
        var tr = $("<tr></tr>");
        tr.append("<td><span style='display: none;'>"+data[i].guardiansId+"</span><span>"+data[i].name+"</span></td>")
            .append("<td>"+data[i].phone+"</td>")
            .append("<td>￥"+data[i].spend+"</td>")
            .append("<td>"+vipLevel+"</td>")
            .append("<td>"+data[i].regDate+"</td>")
            .append("<td>"+data[i].pervLogin+"</td>")
            .append("<td class=\"sidebar-item\">\n" +
                " <button class=\"btn btn-sm btn-info\" title=\"发信息\" onclick=\"showSendMessage('"+data[i].name+"', '"+data[i].guardiansId+"')\"><i class=\"fas fa-envelope\"></i></button>\n" +
                " <button class=\"btn btn-sm btn-warning\" title=\"信息详细\" onclick=\"showInfo('"+data[i].guardiansId+"')\"><i class=\"fas fa-eye\"></i></button>\n" +
                " </td>");
        $("#term-9 .table-responsive table tbody").append(tr);
    }
}

function showStuAndMenu(stuAndMenuList) {
    if (!stuAndMenuList || stuAndMenuList.length === 0) {
        console.log("No menu data available");
        return;
    }

    // 清空历史记录表格
    $("#packageHistoryList").empty();
    
    for (let i = 0; i < stuAndMenuList.length; i++) {
        let currentItem = stuAndMenuList[i];
        
        $.ajax({
            url: "../SelectMenu",
            type: "post",
            dataType: "json",
            data: {
                menuId: currentItem.menuId
            },
            success: function(data) {
                console.log("Menu data received:", data);
                
                // 根据不同状态显示不同的徽章
                let statusBadge;
                switch(currentItem.useStart) {
                    case "使用中":
                        statusBadge = '<span class="badge badge-success">使用中</span>';
                        break;
                    case "未启动":
                        statusBadge = '<span class="badge badge-warning">未启动</span>';
                        break;
                    case "已用完":
                        statusBadge = '<span class="badge badge-secondary">已用完</span>';
                        break;
                    default:
                        statusBadge = '<span class="badge badge-secondary">未知状态</span>';
                }
                
                let row = `
                    <tr>
                        <td>${data.menu.menuName}</td>
                        <td>${data.menu.menu_stopTime}</td>
                        <td>￥${data.menu.menu_money}</td>
                        <td>${statusBadge}</td>
                    </tr>
                `;
                $("#packageHistoryList").append(row);
                
                // 如果是当前使用中的套餐，更新上方的套餐信息
                if (currentItem.useStart === "使用中") {
                    // 显示套餐名称
                    $("#term-42 #currentPackageName").text(data.menu.menuName);
                    
                    // 计算并显示剩余课时
                    let totalCourses = parseInt(data.menu.total_course_num) || 0;
                    let surplusCourses = parseInt(currentItem.surpluClass_count) || 0;
                    let usedCourses = totalCourses - surplusCourses;
                    $("#term-42 .justify-content-between #syu").text(surplusCourses + "课时");
                    
                    // 显示有效期
                    let stopTime = data.menu.menu_stopTime || "未设置";
                    $("#term-42 .justify-content-between #dateyoux").text(stopTime);

                    // 更新进度条
                    let progressPercentage = (usedCourses / totalCourses * 100) || 0;
                    $(".progress-bar").css('width', progressPercentage + '%')
                                    .attr('aria-valuenow', progressPercentage)
                                    .text(progressPercentage.toFixed(0) + '%');
                }
            }
        });
    }
}

function showInfo(guardianId) {
    $.ajax({
        url: "../GetGuardianDetail",
        type: "GET",
        data: {
            guardianId: guardianId
        },
        success: function(data) {
            //隐藏其他模块
            $('.content-module').removeClass('active');
            $('#term-42').addClass('active');

            guardianInit(data.guardian);//显示监护人信息
            ListStudent(data.students);//显示下拉框的学生

            showChildInfo(data.students[0]);//默认显示第一个孩子的信息
            showStuAndMenu(data.stuAndMenuList);
            showClassInof(data.scheduleList);//显示学生课程记录
            // 更新侧边栏状态
            $('.sidebar-item').removeClass('active');
            $('[href="#term-42"]').parent().addClass('active');
            
            // 将当前模块ID存入会话存储
            sessionStorage.setItem('currentModule', 'term-42');
        },
        error: function() {
            alert('获取监护人信息失败，请稍后重试');
        }
    });
}
function guardianInit(guardian) {
    // 设置监护人ID
    $('#guardianDetailId').val(guardian.guardiansId);
    
    // 基本信息填充
    if(guardian.avatar){
        $('#guardianDetailAvatar').attr('src', guardian.avatar);
    }else{
        $('#guardianDetailAvatar').attr('src', '../img/bg/default-avatar.jpg');
    }
    $('#guardianDetailName').text(guardian.name);
    $('#guardianDetailPhone').text(guardian.phone);

    // VIP等级和徽章颜色
    let vipLevel = checkVipLevel(guardian.spend);
    let badgeClass = getBadgeClass(guardian.spend);
    $('#guardianDetailVip').text(vipLevel)
        .removeClass()
        .addClass(`badge badge-${badgeClass}`);

    $('#guardianDetailSpend').text(`￥${guardian.spend}`);
    $('#guardianDetailRegDate').text(guardian.regDate);
    $('#guardianDetailLastLogin').text(guardian.pervLogin);
}


//列出孩子的下拉框
function ListStudent(students) {
    $("#childrenSelector").empty();
    students.forEach(student => {
        var option = $("<option>").val(student.stuId).text(student.stuName);
        $("#childrenSelector").append(option);
    });
}

//切换孩子下拉框
$("#term-42").on("change", "#childrenSelector", function () {
    var stuId = $(this).val();
    $.ajax("../AboutStuInfo", {
        data: { stuId: stuId },
        success: function (data) {
            showChildInfo(data.student);//显示学生信息
            showStuAndMenu(data.stuAndMenuList);//显示学生的套餐信息
            showClassInof(data.scheduleList);//显示学生课程记录
        }

    });
});
//显示上课记��信息
function showClassInof(data) {
    // 清空现有的课程记录
    $(".course-list").empty();
    
    // 添加固定高度的容器样式
    $(".course-list").css({
        'height': '400px',
        'overflow-y': 'auto',
        'padding-right': '10px'
    });
    
    // 如果没有数据，显示提示信息
    if (!data || data.length === 0) {
        $(".course-list").append('<div class="text-center text-muted">暂无上课记录</div>');
        return;
    }
    
    // 循环添加课程记录卡片
    data.forEach(tiem => {
        let statusBadge = tiem.ClassStatus === "已到"
            ? '<span class="badge badge-success">已到</span>'
            : '<span class="badge badge-danger">缺席</span>';
            
        let data = null;
        if(tiem.ClassIndex==="第一节课"){
            data = "AM 8.00~9.00";
        }else if(tiem.ClassIndex==="第二节课"){
            data = "AM 9.30~10.30";
        }else if(tiem.ClassIndex==="第三节课"){
            data = "PM 14.00~15.00";
        }else if(tiem.ClassIndex==="第四节课"){
            data = "PM 15.30~16.30";
        }
        
        let courseCard = `
            <div class="course-card mb-3" style="background: #f8f9fa; padding: 15px; border-radius: 8px;">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <h6 class="mb-0" style="font-size: 0.95rem;">${JSON.parse(tiem.ClassInfo).class}</h6>
                    ${statusBadge}
                </div>
                <div class="course-info">
                    <div class="row">
                        <div class="col-6">
                            <small class="text-muted d-block">
                                <i class="fas fa-user-tie mr-2"></i>${JSON.parse(tiem.ClassInfo).teacher}
                            </small>
                            <small class="text-muted d-block">
                                <i class="fas fa-map-marker-alt mr-2"></i>${JSON.parse(tiem.ClassInfo).site}
                            </small>
                        </div>
                        <div class="col-6 text-right">
                            <small class="text-muted d-block">${tiem.time}</small>
                            <small class="text-muted d-block">${data}</small>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        $(".course-list").append(courseCard);
    });

    // 更新穿梭框数据
    layui.transfer.reload('key123', {
        data: data.map(item => ({
            value: item.id,
            title: item.name,
            disabled: item.disabled
        }))
    });
}
//显示孩子信息
function showChildInfo(student) {
    console.log(student);
    $("#term-42 .child-card .badge-primary")
        .text(student.sex)
        .addClass('badge-xs');
    $("#term-42 .child-card .mb-0").text(student.stuName);
    $("#term-42 .child-card .text-muted span").eq(0).text(student.stuId);
    $("#term-42 .child-card .text-muted span").eq(1).text(student.age);
    $("#term-42 .child-card .rounded-circle").attr("src", student.avatar);
}

// 获取VIP徽章样式类
function getBadgeClass(spend) {
    if (spend >= 6000) {
        return 'primary';    // VIP 3
    } else if (spend >= 4000) {
        return 'info';       // VIP 2
    } else if (spend >= 2000) {
        return 'warning';    // VIP 1
    } else {
        return 'secondary';  // 普通会员
    }
}

// 双击头像放大预览
$(document).on('dblclick', '#guardianDetailAvatar', function() {
    var imgSrc = $(this).attr('src');
    $("#avatarPreviewLarge").attr('src', imgSrc);
    $("#avatarPreviewModal").modal('show');
});

function pagIng(pagIng,page){
    var pagination = $("#term-9 .pagination");
    pagination.append("<li class=\"page-item\"><a class=\"page-link\" href=\"#\" onclick=InitGuardians(PageIndex-1)>上一页</a></li>");
    for(let i = 1;i <= pagIng;i++){
        var text = $("<li class=\"page-item event\"><a class=\"page-link\" href=\"#\">"+i+"</a></li>");
        pagination.append(text);
    }
    pagination.append("<li class=\"page-item\"><a class=\"page-link last\" href=\"#\" onclick=InitGuardians(PageIndex+1)>下一页</a></li>");
    pagination.find("li").eq(page).addClass("active");
    if(page === 1){
        pagination.find("li").eq(0).addClass("disabled");
    }else if (page === pagIng){
        pagination.find("li").eq(pagIng+1).addClass("disabled");
    }
}
$("#term-9 .pagination").on("click",".event a",function (){
    InitGuardians($(this).text());
});
function checkVipLevel(spend) {
    if (spend >= 6000) {
        return "VIP 3";
    } else if (spend >= 4000) {
        return "VIP 2";
    } else if (spend >= 2000) {
        return "VIP 1";
    } else {
        return "普通会员";
    }
}
//搜索事件
$("#term-9 .btn-block").click(function (){
    InitGuardians();
    $("#term-9 .col-md-4 input").val("");
});

// 头像双击放大预览
$("#guardianAvatarPreview").dblclick(function() {
    var imgSrc = $(this).attr('src');
    $("#avatarPreviewLarge").attr('src', imgSrc);
    $("#avatarPreviewModal").modal('show');
});

// 头像预览功能
$("#guardianAvatarInput").change(function() {
    if (this.files && this.files[0]) {
        var formData = new FormData();
        formData.append('file', this.files[0]);

        // 先预览图片
        var reader = new FileReader();
        reader.onload = function(e) {
            $("#guardianAvatarPreview").attr("src", e.target.result)
                .css('cursor', 'pointer')
                .attr('title', '双击查看大图');
        }
        reader.readAsDataURL(this.files[0]);

        // 上传图片到服务器
        $.ajax({
            url: '../UploadImage',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if(response.success) {
                    // 保存服务器返回的图片路径
                    $("#guardianAvatarPreview").data('serverPath', response.imagePath);
                } else {
                    alert("图片上传失败：" + response.message);
                }
            }
        });
    }
});

// 修改保存监护人函数
function saveNewGuardian() {
    // 表单验证
    var guardianName = $("#addGuardianName").val();
    var guardianAge = $("#addGuardianAge").val();
    var guardianSex = $("input[name='guardianGender']:checked").val();
    if (!guardianName || !guardianAge || !guardianSex) {
        alert("请填写完整信息");
        return;
    }

    // 获取图片路径（优先使用服务器路径，如果没有使用当前显示的路径）
    var avatarPath = $("#guardianAvatarPreview").data('serverPath') || $("#guardianAvatarPreview").attr('src');

    // 发送添加请求
    $.ajax({
        url: "../AddGuardian",
        type: "POST",
        data: {
            name: guardianName,
            age: guardianAge,
            gender: guardianSex,
            phone: $("#addGuardianPhone").val(),
            avatar: avatarPath
        },
        success: function(data) {
            alert(data);
            if(data === "添加成功") {
                // 关闭模态框
                $("#addGuardianModal").modal("hide");
                // 刷新监护人列表
                InitGuardians(1);
            } else {
                alert("添加失败：" + data);
            }
        }
    });
}

// 监听模态框显示事件，清空表单
$('#addGuardianModal').on('show.bs.modal', function () {
    // 清空所有输入框的值
    $("#addGuardianName").val("");
    $("#addGuardianAge").val("");
    $("#addGuardianPhone").val("");
    
    // 重置性别选择为默认值（男）
    $("#genderMale").prop("checked", true);
    $("#genderFemale").prop("checked", false);
    
    // 重置头像为默认图片
    $("#guardianAvatarPreview").attr("src", "../img/bg/default-avatar.jpg");
    $("#guardianAvatarInput").val("");
    
    // 移除所有可能的错误提示样式
    $(".form-control").removeClass("is-invalid");
    $(".invalid-feedback").remove();
});

// 添加排序状态变量
var sortConfig = {
    column: '', // 当前排序的列
    order: '' // 排序方向：asc 升序，desc 降序
};

// 给排序图标添���点击事件
$(".sort-icon").click(function(e) {
    e.stopPropagation(); // 阻止事件冒泡
    
    // 获取排序信息
    var column = $(this).closest('th').text().trim();
    if(column === "消费总额") {
        column = "spend";
    }else if(column === "注册时间") {
        column = "regDate";
    }
    var order = $(this).data('sort');
    
    // 移除所有图标的激活状态
    $(".sort-icon").removeClass('active');
    // 激活当前点击的图标
    $(this).addClass('active');
    
    // 发送排序请求
    $.ajax({
        url: "../ListGuardians",
        type: "get",
        dataType: "json",
        data: {
            where: $("#term-9 .col-md-4 .form-control").val(),
            page: PageIndex,
            sortColumn: column,
            sortOrder: order
        },
        success: function(data) {
            if(data.message === "获取数据成功") {
                
                $("#term-9 .table-responsive table tbody").empty();
                ListGuardians(data.guardiansList);
            }
        }
    });
});

// 修改显示发信息模态框函数
function showSendMessage(recipientName, recipientId) {
    $("#messageRecipient").val(recipientName);
    $("#messageRecipientId").val(recipientId);
    $("#messageTitle").val("");
    $("#messageContent").val("");
    $("#messageImage").val("");
    $("#imagePreview").hide();//隐藏
    $("#sendMessageModal").modal("show");
}

// 图片预览
$("#messageImage").change(function() {
    if (this.files && this.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            $("#previewImg").attr("src", e.target.result);
            $("#imagePreview").show();
        }
        reader.readAsDataURL(this.files[0]);
    }
});

// 修改发信息函数
function sendMessage() {
    var recipientId = $("#messageRecipientId").val();  // 使用隐藏的ID
    var recipientName = $("#messageRecipient").val();
    var title = $("#messageTitle").val();
    var content = $("#messageContent").val();
    var imageFile = $("#messageImage")[0].files[0].name;
    alert(imageFile);
    alert("收件人: " + recipientName + "\n" +
        "ID: " + recipientId + "\n" +
        "标题: " + title + "\n" +
        "内容: " + content + "\n" +
        "图片: " + imageFile);

    // 表单验证
    if(!title || !content) {
        alert("请填写标题和内容");
        return;
    }

    // 发送请求
    $.ajax({
        url: "../SendMessage",
        type: "POST",
        data: {
            recipientId: recipientId,
            recipientName: recipientName,
            title: title,
            content: content,
            image: imageFile
        },
        success: function(response) {
            alert("发送成功");
            $("#sendMessageModal").modal("hide");
        }
    });
}

